﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.TechnologyAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command;

public class UpdateTechnologyCommand : TechnologyEditRequestDto, IRequest<Result<TechnologyInfoResponseDto>>
{
    public int Id { get; set; }
}

public class
    UpdateTechnologyCommandHandler : IRequestHandler<UpdateTechnologyCommand, Result<TechnologyInfoResponseDto>>
{
    private readonly ITechnologyRepository _technologyRepository;
    private readonly IMapper _mapper;

    public UpdateTechnologyCommandHandler(ITechnologyRepository technologyRepository,
        IMapper mapper)
    {
        _technologyRepository = technologyRepository;
        _mapper = mapper;
    }

    public async Task<Result<TechnologyInfoResponseDto>> Handle(UpdateTechnologyCommand request,
        CancellationToken cancellationToken)
    {
        var technology = await _technologyRepository.Get(request.Id);
        if (technology != null)
        {
            technology.Update(request.Code, request.Name, request.Quality,
                request.StandardBom.Id, request.StandardBom.Code, request.StandardBom.Name,
                request.Description);

            foreach (var item in request.Items)
            {
                if (item.Key > 0)
                {
                    technology.UpdateItem(item.Key, item.ProcessId, item.ProcessCode, item.ProcessName, item.Sort,
                        item.TakeTime);
                }
                else
                {
                    technology.AddItem(item.ProcessId, item.ProcessCode, item.ProcessName, item.Sort, item.TakeTime);
                }
            }
        }

        await _technologyRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return await Result<TechnologyInfoResponseDto>.SuccessAsync(
            _mapper.Map<TechnologyInfoResponseDto>(technology));
    }
}